<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告框 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        effect="dark"
      >
      </el-alert>
      <!-- 级联选择器 -->
      <div style="margin-top: 20px">
        请选择商品分类
        <el-cascader
          v-model="selectedCate"
          :options="cateList"
          :props="{
            label: 'cat_name',
            value: 'cat_id',
            expandTrigger: 'hover'
          }"
          @change="handleChange"
        ></el-cascader>
      </div>

      <!-- tab栏 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addCatedialogVisible = true"
          >
            添加参数
          </el-button>
          <!-- 参数内容 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="primary"
                  closable
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <!-- eslint-disable -->
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                ></el-button>
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addCatedialogVisible = true"
          >
            添加参数
          </el-button>

          <!-- 参数内容 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="primary"
                  closable
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <!-- eslint-disable -->
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                ></el-button>
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addCatedialogVisible"
      width="35%"
      @close="addCateFormClose"
    >
      <el-form label-width="80px" ref="addCateForm">
        <el-form-item label="参数名称">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams"> 确 定 </el-button>
      </span>
    </el-dialog>

    <!-- 修改参数 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editCatedialogVisible"
      width="35%"
    >
      <el-form label-width="80px">
        <el-form-item label="参数名称">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditParams"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      cateList: [],
      selectedCate: [],
      activeName: 'many', /* 默认选中的标签 */
      manyTableData: [], // 动态数据
      onlyTableData: [], // 静态数据
      addCatedialogVisible: false, // 添加参数对话框
      addParamsForm: {
        attr_name: ''
      },
      editCatedialogVisible: false, // 修改参数对话框
      editParamsForm: {},
      inputVisible: false,
      inputValue: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取参数列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败！')
      this.cateList = res.data
      // console.log(this.cateList)
    },
    handleChange () {
      // console.log(this.selectedCate)
      if (this.selectedCate.length !== 3) {
        this.selectedCate = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      this.getCateData()
    },
    handleClick (tab, event) {
      // console.log(tab, event)
      this.getCateData()
    },
    // 获取参数数据
    async getCateData () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('请选择三级商品分类！')
      res.data.forEach(item => {
        item.inputVisible = false
        item.inputValue = ''
        if (item.attr_vals.trim() === '') {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(' ')
        }
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
        // console.log(this.manyTableData)
      } else {
        this.onlyTableData = res.data
        // console.log(this.onlyTableData)
      }
    },
    // 添加参数
    async addParams () {
      const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,
        { attr_name: this.addParamsForm.attr_name, attr_sel: this.activeName })
      if (res.meta.status !== 201) return this.$message.error('添加参数数据失败！')
      this.$message.success('添加参数成功！')
      this.getCateData()
      this.addCatedialogVisible = false
    },
    showEditDialog (row) {
      this.editParamsForm = row
      this.editCatedialogVisible = true
    },
    // 提交修改参数名称
    async saveEditParams () {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
        { attr_name: this.editParamsForm.attr_name, attr_sel: this.activeName })
      if (res.meta.status !== 200) return this.$message.error('修改参数名称失败！')
      this.$message.success('修改参数名称成功！')
      this.getCateData()
      this.editCatedialogVisible = false
    },
    // 删除按钮处理函数
    removeParams (row) {
      console.log(row)
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error('删除数据失败！')
        this.$message.success('删除数据成功！')
        this.getCateData()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    addCateFormClose () {
      this.$refs.addCateForm.resetFields()
    },
    async saveAttr (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('操作失败！')
      this.$message.success('操作成功！')
    },
    async handleInputConfirm (row) {
      if (row.inputValue === '') {
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttr(row)
    },
    showInput (row) {
      row.inputVisible = true
      // 数据变了，但是视图并不能立即更新，所以我们需要$nextTick来获取
      this.$nextTick(() => {
        // this.$refs.saveTagInput.$refs.input获取原生的input
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleClose (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttr(row)
    }
  },
  computed: {
    isBtnDisabled: function () {
      return this.selectedCate.length < 3
    },
    cateId () {
      return this.selectedCate[this.selectedCate.length - 1]
    },
    titleText () {
      return this.activeName === 'many' ? '动态参数' : '静态参数'
    }
  }
}
</script>

<style scoped lang="less">
.el-cascader {
  width: 260px;
}
.el-tag {
  margin: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
}
</style>
